import { app, BrowserWindow, Menu, ipcMain, dialog } from 'electron';
import * as path from 'path';
import * as fs from 'fs';

// 主进程日志发送函数
let mainWindow: BrowserWindow | null = null;

const sendLogToRenderer = (message: string) => {
  if (mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.webContents.send('main-process-log', message);
  }
};

// 重写console.log以同时输出到主进程和渲染进程
const originalLog = console.log;
const originalError = console.error;
const originalWarn = console.warn;
const originalInfo = console.info;

console.log = (...args) => {
  originalLog(...args);
  sendLogToRenderer(args.join(' '));
};

console.error = (...args) => {
  originalError(...args);
  sendLogToRenderer(`ERROR: ${args.join(' ')}`);
};

console.warn = (...args) => {
  originalWarn(...args);
  sendLogToRenderer(`WARN: ${args.join(' ')}`);
};

console.info = (...args) => {
  originalInfo(...args);
  sendLogToRenderer(`INFO: ${args.join(' ')}`);
};

// 设置应用 ID，这对于任务栏图标显示很重要
app.setAppUserModelId('com.picshare.client');

// 配置文件路径（使用用户数据目录）
const getConfigPath = () => {
  // 使用用户数据目录，确保有写入权限
  const userDataPath = app.getPath('userData');
  return path.join(userDataPath, 'config.json');
};

// 读取配置
const readConfig = () => {
  try {
    const configPath = getConfigPath();
    if (fs.existsSync(configPath)) {
      const data = fs.readFileSync(configPath, 'utf8');
      return JSON.parse(data);
    }
    return { apiKey: '', watchDirectory: '' };
  } catch (error) {
    console.error('读取配置文件失败:', error);
    return { apiKey: '', watchDirectory: '' };
  }
};

// 保存配置
const saveConfig = (config: any) => {
  try {
    const configPath = getConfigPath();
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    return true;
  } catch (error) {
    console.error('保存配置文件失败:', error);
    return false;
  }
};

function createWindow(): void {
  console.log('Creating window...');
  console.log('App is packaged:', app.isPackaged);
  console.log('App path:', app.getAppPath());
  console.log('__dirname:', __dirname);

  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    icon: path.join(app.getAppPath(), 'build', 'icon.ico'),
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js'),
      webSecurity: false // 开发环境禁用跨域检查
    },
    titleBarStyle: 'default',
    show: false,
    backgroundColor: '#f5f5f5'
  });

  const isDev = !app.isPackaged; // 检测是否为打包环境
  console.log('Is dev mode:', isDev);
  
  if (isDev) {
    console.log('Loading URL: http://localhost:3000');
    mainWindow.loadURL('http://localhost:3000').then(() => {
      console.log('URL loaded successfully');
      mainWindow?.webContents.openDevTools();
    }).catch(err => {
      console.error('Failed to load URL:', err);
    });
  } else {
    const filePath = path.join(__dirname, '../dist-renderer/index.html');
    console.log('=== 生产环境模式 ===');
    console.log('App path:', app.getAppPath());
    console.log('__dirname:', __dirname);
    console.log('Loading file:', filePath);

    const fs = require('fs');
    console.log('File exists:', fs.existsSync(filePath));

    if (fs.existsSync(filePath)) {
      console.log('File size:', fs.statSync(filePath).size);
      console.log('File content preview:', fs.readFileSync(filePath, 'utf8').substring(0, 200));
    } else {
      console.log('Available files:');
      const appPath = app.getAppPath();
      try {
        const files = fs.readdirSync(appPath);
        console.log('Root directory:', files);

        if (fs.existsSync(path.join(appPath, 'dist-renderer'))) {
          const distFiles = fs.readdirSync(path.join(appPath, 'dist-renderer'));
          console.log('dist-renderer directory:', distFiles);
        }
      } catch (err) {
        console.error('Error reading directory:', err);
      }
    }

    mainWindow.loadFile(filePath).then(() => {
      console.log('✅ File loaded successfully');
      // 生产环境不再自动打开开发者工具
      console.log('🔧 生产环境已部署，开发者工具已关闭');
    }).catch(err => {
      console.error('❌ Failed to load file:', err);

      // 显示错误页面
      mainWindow?.loadURL(`data:text/html,
        <html>
          <head><title>调试信息</title></head>
          <body style="font-family: monospace; padding: 20px;">
            <h1>🔍 调试信息</h1>
            <p><strong>App Path:</strong> ${app.getAppPath()}</p>
            <p><strong>__dirname:</strong> ${__dirname}</p>
            <p><strong>Tried to load:</strong> ${filePath}</p>
            <p><strong>File exists:</strong> ${fs.existsSync(filePath)}</p>
            <p><strong>Error:</strong> ${err.message}</p>
            <p><strong>Stack:</strong> <pre>${err.stack}</pre></p>
          </body>
        </html>
      `);
    });
  }

  mainWindow?.once('ready-to-show', () => {
    console.log('Window ready to show');
    mainWindow?.show();
  });

  mainWindow?.on('closed', () => {
    console.log('Window closed');
    mainWindow = null;
  });

  // 添加错误处理
  mainWindow?.webContents.on('did-fail-load', (event, errorCode, errorDesc) => {
    console.error('Failed to load content:', errorCode, errorDesc);
    // 重试加载
    setTimeout(() => {
      if (mainWindow) {
        const isDev = !app.isPackaged; // 检测是否为打包环境
        if (isDev) {
          mainWindow.loadURL('http://localhost:3000');
        } else {
          mainWindow.loadFile(path.join(__dirname, '../dist-renderer/index.html'));
        }
      }
    }, 1000);
  });

  // 监听渲染进程崩溃
  mainWindow?.on('unresponsive', () => {
    console.log('Window became unresponsive');
  });

  mainWindow?.on('responsive', () => {
    console.log('Window became responsive again');
  });
}

function createMenu(): void {
  const template: Electron.MenuItemConstructorOptions[] = [
    {
      label: '文件',
      submenu: [
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { role: 'undo', label: '撤销' },
        { role: 'redo', label: '重做' },
        { type: 'separator' },
        { role: 'cut', label: '剪切' },
        { role: 'copy', label: '复制' },
        { role: 'paste', label: '粘贴' }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

// IPC处理程序
ipcMain.handle('select-directory', async () => {
  const result = await dialog.showOpenDialog(mainWindow!, {
    properties: ['openDirectory']
  });
  return result.filePaths[0] || '';
});

ipcMain.handle('select-file', async () => {
  const result = await dialog.showOpenDialog(mainWindow!, {
    properties: ['openFile', 'multiSelections'],
    filters: [
      { 
        name: '图片文件', 
        extensions: [
          // 常见图片格式
          'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif',
          // RAW格式
          'arw', 'cr2', 'cr3', 'nef', 'orf', 'rw2', 'pef', 'srw',
          'dng', 'raf', '3fr', 'kdc', 'mos', 'mrw', 'nrw', 'gpr'
        ] 
      }
    ]
  });
  return result.filePaths || [];
});

ipcMain.handle('get-config', () => {
  return readConfig();
});

ipcMain.handle('save-config', (event, config) => {
  return saveConfig(config);
});

// 文件系统监听相关 IPC 处理程序
ipcMain.handle('readdir', async (event, directoryPath) => {
  try {
    const files = await fs.promises.readdir(directoryPath);
    return files;
  } catch (error) {
    console.error('读取目录失败:', error);
    return [];
  }
});

ipcMain.handle('stat', async (event, filePath) => {
  try {
    const stats = await fs.promises.stat(filePath);
    return {
      size: stats.size,
      mtime: stats.mtime.getTime(),
      isFile: stats.isFile(),
      isDirectory: stats.isDirectory()
    };
  } catch (error) {
    console.error('获取文件状态失败:', error);
    throw error;
  }
});

ipcMain.handle('readFileAsArrayBuffer', async (event, filePath) => {
  try {
    const buffer = await fs.promises.readFile(filePath);
    return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
  } catch (error) {
    console.error('读取文件失败:', error);
    throw error;
  }
});

// ===== 主进程文件监听器 =====
// 用于解决渲染进程定时器节流问题

// 文件信息接口
interface FileInfo {
  path: string;
  name: string;
  size: number;
  mtime: number;
}

// 主进程文件监听器类
class MainProcessFileListener {
  private directoryPath: string;
  private interval: number;
  private processedFiles: Set<string> = new Set();
  private fileSizes: Map<string, { size: number; lastCheck: number; checkCount: number }> = new Map();
  private intervalId: NodeJS.Timeout | null = null;
  private mainWindow: BrowserWindow | null;
  private isRunning: boolean = false;

  // 节流检测相关
  private scanCount: number = 0;
  private lastScanTime: number = 0;
  private scanIntervalHistory: number[] = [];
  private maxHistoryLength: number = 20;
  private lastThrottleLogTime: number = 0;

  constructor(directoryPath: string, interval: number = 1000, mainWindow: BrowserWindow) {
    this.directoryPath = directoryPath;
    this.interval = interval;
    this.mainWindow = mainWindow;
    console.log(`🎯 [主进程] 创建文件监听器: ${directoryPath} (间隔: ${interval}ms)`);
  }

  start(): void {
    if (this.isRunning) {
      console.log('🔄 [主进程] 文件监听器已在运行');
      return;
    }

    console.log('🚀 [主进程] 启动文件监听器');

    try {
      // 重置节流检测状态
      this.scanCount = 0;
      this.lastScanTime = 0;
      this.scanIntervalHistory = [];
      this.lastThrottleLogTime = Date.now();

      console.log(`🔧 [主进程] 节流检测已初始化`);
      console.log(`   ├─ 期望扫描间隔: ${this.interval}ms`);
      console.log(`   ├─ 历史记录长度: ${this.maxHistoryLength}`);
      console.log(`   └─ 检测模式: 已启用`);

      // 构建初始文件列表（不上传已有文件）
      this.buildInitialFileList();

      // 启动定时扫描（主进程不受浏览器节流影响）
      this.intervalId = setInterval(() => {
        this.scanDirectory().catch(error => {
          console.error('❌ [主进程] 文件扫描失败:', error);
        });
      }, this.interval);

      this.isRunning = true;
      console.log(`✅ [主进程] 文件监听器已启动，已建立初始文件列表，现有 ${this.processedFiles.size} 个文件将被跳过`);
    } catch (error) {
      console.error('❌ [主进程] 启动文件监听器失败:', error);
      throw error;
    }
  }

  stop(): void {
    if (!this.isRunning) {
      console.log('ℹ️ [主进程] 文件监听器未运行');
      return;
    }

    console.log('⏹️ [主进程] 停止文件监听器');

    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }

    // 输出节流检测最终报告
    if (this.scanCount > 0) {
      console.log(`📊 [主进程] 节流检测最终报告:`);
      console.log(`   ├─ 总扫描次数: ${this.scanCount}`);
      console.log(`   ├─ 历史记录数: ${this.scanIntervalHistory.length}`);

      if (this.scanIntervalHistory.length > 0) {
        const avgInterval = this.scanIntervalHistory.reduce((a, b) => a + b, 0) / this.scanIntervalHistory.length;
        const maxInterval = Math.max(...this.scanIntervalHistory);
        const minInterval = Math.min(...this.scanIntervalHistory);
        const maxThrottleRatio = maxInterval / this.interval;

        console.log(`   ├─ 平均间隔: ${avgInterval.toFixed(2)}ms`);
        console.log(`   ├─ 最大间隔: ${maxInterval}ms`);
        console.log(`   ├─ 最小间隔: ${minInterval}ms`);
        console.log(`   ├─ 最大节流倍数: ${maxThrottleRatio.toFixed(2)}x`);

        // 性能评估
        if (maxThrottleRatio <= 1.5) {
          console.log(`   ├─ 性能评估: 🟢 优秀 (无明显节流)`);
        } else if (maxThrottleRatio <= 3) {
          console.log(`   ├─ 性能评估: 🟡 良好 (轻微节流)`);
        } else if (maxThrottleRatio <= 10) {
          console.log(`   ├─ 性能评估: 🟠 一般 (中度节流)`);
        } else {
          console.log(`   ├─ 性能评估: 🔴 较差 (严重节流)`);
        }
      }

      console.log(`   └─ 主进程监听: ${this.interval === 1000 ? '✅ 已生效' : '⚠️ 配置异常'}`);
    }

    // 清理文件大小记录
    const fileSizesCount = this.fileSizes.size;
    this.fileSizes.clear();
    if (fileSizesCount > 0) {
      console.log(`🧹 [主进程] 清理了 ${fileSizesCount} 个文件大小记录`);
    }

    // 清理节流检测数据
    this.scanCount = 0;
    this.lastScanTime = 0;
    this.scanIntervalHistory = [];
    this.lastThrottleLogTime = 0;

    this.isRunning = false;
    console.log('✅ [主进程] 文件监听器已停止');
  }

  // 建立初始文件列表（启动时调用，不上传已有文件）
  private async buildInitialFileList(): Promise<void> {
    try {
      const files = await fs.promises.readdir(this.directoryPath);
      let initialCount = 0;

      for (const fileName of files) {
        const filePath = path.join(this.directoryPath, fileName);

        try {
          // 获取文件状态
          const stats = await fs.promises.stat(filePath);

          // 只处理文件（不是目录）
          if (!stats.isFile()) {
            continue;
          }

          // 检查文件大小（跳过空文件）
          if (stats.size === 0) {
            continue;
          }

          // 检查文件扩展名（只处理图片文件）
          if (!this.isImageFile(fileName)) {
            continue;
          }

          // 跳过系统文件和隐藏文件
          if (this.isSystemFile(fileName)) {
            continue;
          }

          // 添加到已处理列表（标记为"已存在"，不上传）
          this.processedFiles.add(filePath);
          initialCount++;

        } catch (error) {
          // 跳过无法获取状态的文件
          continue;
        }
      }

      console.log(`📋 [主进程] 建立初始文件列表完成，发现 ${initialCount} 个现有图片文件`);

    } catch (error) {
      console.error('❌ [主进程] 建立初始文件列表失败:', error);
      throw error;
    }
  }

  private async scanDirectory(): Promise<void> {
    if (!this.isRunning) {
      return;
    }

    // 节流检测：记录扫描时间和间隔
    const now = Date.now();
    this.scanCount++;

    if (this.lastScanTime > 0) {
      const actualInterval = now - this.lastScanTime;
      this.scanIntervalHistory.push(actualInterval);

      // 保持历史记录在指定长度内
      if (this.scanIntervalHistory.length > this.maxHistoryLength) {
        this.scanIntervalHistory.shift();
      }

      // 节流检测逻辑
      const expectedInterval = this.interval;
      const throttleRatio = actualInterval / expectedInterval;

      // 每30秒输出一次节流状态（避免日志过多）
      if (now - this.lastThrottleLogTime > 30000) {
        const avgInterval = this.scanIntervalHistory.reduce((a, b) => a + b, 0) / this.scanIntervalHistory.length;
        const maxInterval = Math.max(...this.scanIntervalHistory);
        const minInterval = Math.min(...this.scanIntervalHistory);

        console.log(`📊 [主进程] 节流检测报告 #${this.scanCount}:`);
        console.log(`   ├─ 期望间隔: ${expectedInterval}ms`);
        console.log(`   ├─ 实际间隔: ${actualInterval}ms`);
        console.log(`   ├─ 平均间隔: ${avgInterval.toFixed(2)}ms`);
        console.log(`   ├─ 最大间隔: ${maxInterval}ms`);
        console.log(`   ├─ 最小间隔: ${minInterval}ms`);
        console.log(`   ├─ 节流倍数: ${throttleRatio.toFixed(2)}x`);
        console.log(`   ├─ 扫描次数: ${this.scanCount}`);
        console.log(`   └─ 监听状态: ${this.isRunning ? '运行中' : '已停止'}`);

        // 检测到明显节流时的警告
        if (throttleRatio > 2) {
          console.log(`⚠️ [主进程] 检测到节流！间隔被延长了 ${throttleRatio.toFixed(2)} 倍`);
        }

        // 检测到异常长间隔（可能是系统休眠等）
        if (actualInterval > 60000) {
          console.log(`🚨 [主进程] 检测到异常长间隔: ${actualInterval}ms (可能是系统休眠或严重延迟)`);
        }

        this.lastThrottleLogTime = now;
      }
    }

    this.lastScanTime = now;

    try {
      const files = await fs.promises.readdir(this.directoryPath);
      let newFileCount = 0;

      for (const fileName of files) {
        const filePath = path.join(this.directoryPath, fileName);

        // 跳过已处理的文件
        if (this.processedFiles.has(filePath)) {
          continue;
        }

        try {
          // 获取文件状态
          const stats = await fs.promises.stat(filePath);

          // 检查是否为文件（不是目录）
          if (!stats.isFile()) {
            continue;
          }

          // 检查文件大小（跳过空文件）
          if (stats.size === 0) {
            continue;
          }

          // 检查文件扩展名（只处理图片文件）
          if (!this.isImageFile(fileName)) {
            continue;
          }

          // 跳过系统文件和隐藏文件
          if (this.isSystemFile(fileName)) {
            continue;
          }

          // 文件大小稳定性检查 - 防止相机拍摄时重复上传
          const now = Date.now();
          const fileRecord = this.fileSizes.get(filePath);

          if (fileRecord) {
            // 文件已记录，检查大小是否稳定
            if (fileRecord.size === stats.size) {
              // 大小没有变化，增加检查计数
              fileRecord.checkCount++;
              fileRecord.lastCheck = now;

              // 连续3次大小不变，才认为是完整文件
              if (fileRecord.checkCount >= 3) {
                // 这是稳定的新文件！
                newFileCount++;

                // 创建文件信息对象
                const fileInfo: FileInfo = {
                  path: filePath,
                  name: fileName,
                  size: stats.size,
                  mtime: stats.mtime.getTime()
                };

                // 添加到已处理列表
                this.processedFiles.add(filePath);
                // 从大小记录中移除
                this.fileSizes.delete(filePath);

                // 通知渲染进程
                this.notifyNewFile(fileInfo);

                console.log(`🆕 [主进程] 发现稳定的新图片: ${fileName} (${this.formatFileSize(stats.size)})`);
              }
            } else {
              // 大小发生变化，重置检查计数
              console.log(`📊 [主进程] 文件大小变化: ${fileName} ${fileRecord.size} -> ${stats.size}`);
              fileRecord.size = stats.size;
              fileRecord.checkCount = 1;
              fileRecord.lastCheck = now;
            }
          } else {
            // 首次检测到文件，记录大小
            console.log(`🔍 [主进程] 首次检测文件: ${fileName} (${this.formatFileSize(stats.size)})`);
            this.fileSizes.set(filePath, {
              size: stats.size,
              lastCheck: now,
              checkCount: 1
            });
          }

        } catch (error) {
          console.warn(`⚠️ [主进程] 无法获取文件状态: ${filePath}`, error);
        }
      }

      // 如果有新文件，输出汇总
      if (newFileCount > 0) {
        console.log(`📊 [主进程] 本次扫描发现 ${newFileCount} 个新文件`);
      }

      // 清理过期的文件大小记录（防止内存泄漏）
      this.cleanupExpiredFileSizes();

    } catch (error) {
      console.error('❌ [主进程] 扫描目录失败:', error);
    }
  }

  // 清理过期的文件大小记录
  private cleanupExpiredFileSizes(): void {
    const now = Date.now();
    const expiredFiles: string[] = [];

    this.fileSizes.forEach((record, filePath) => {
      // 超过5分钟没有更新的记录，清理掉
      if (now - record.lastCheck > 5 * 60 * 1000) {
        expiredFiles.push(filePath);
      }
    });

    expiredFiles.forEach(filePath => {
      this.fileSizes.delete(filePath);
      console.log(`🧹 [主进程] 清理过期的文件大小记录: ${path.basename(filePath)}`);
    });

    if (expiredFiles.length > 0) {
      console.log(`🧹 [主进程] 总共清理了 ${expiredFiles.length} 个过期的文件大小记录`);
    }
  }

  // 通知渲染进程发现新文件
  private notifyNewFile(fileInfo: FileInfo): void {
    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      this.mainWindow.webContents.send('new-file-detected', fileInfo);
      console.log(`📤 [主进程] 已通知渲染进程新文件: ${fileInfo.name}`);
    } else {
      console.warn(`⚠️ [主进程] 无法通知渲染进程，窗口已关闭`);
    }
  }

  // 检查是否为图片文件
  private isImageFile(fileName: string): boolean {
    const imageExtensions = [
      // 常见图片格式
      'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif',
      'heic', 'heif', 'ico', 'svg',
      // RAW格式
      'arw', 'cr2', 'cr3', 'nef', 'orf', 'rw2', 'pef', 'srw',
      'dng', 'raf', '3fr', 'kdc', 'mos', 'mrw', 'nrw', 'gpr'
    ];

    const extension = fileName.toLowerCase().split('.').pop();
    return extension ? imageExtensions.includes(extension) : false;
  }

  // 检查是否为系统文件
  private isSystemFile(fileName: string): boolean {
    const systemFilePatterns = [
      // macOS系统文件
      '.DS_Store', '._', '.localized',
      // Windows系统文件
      'Thumbs.db', 'desktop.ini',
      // 隐藏文件（以点开头）
      '^[.]',
      // 系统目录
      'Photos Library.photoslibrary',
      'iPhoto Library.photolibrary',
      'Aperture Library.aplibrary'
    ];

    return systemFilePatterns.some(pattern => {
      if (pattern.startsWith('^')) {
        return new RegExp(pattern).test(fileName);
      }
      return fileName.includes(pattern) || fileName.toLowerCase().startsWith(pattern.toLowerCase());
    });
  }

  // 格式化文件大小
  private formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
}

// 监听相关的IPC接口
ipcMain.handle('start-listening', async (event, directoryPath) => {
  console.log(`🎯 [IPC] 收到启动监听请求: ${directoryPath}`);
  console.log(`🎯 [IPC] 主窗口状态: ${mainWindow ? '正常' : '未初始化'}`);
  console.log(`🎯 [IPC] 主窗口是否已销毁: ${mainWindow?.isDestroyed() ? '是' : '否'}`);

  if (!mainWindow) {
    console.error('❌ [IPC] 主窗口未初始化');
    return false;
  }

  // 停止现有监听器
  if (fileListener) {
    console.log('🔄 [IPC] 停止现有监听器');
    fileListener.stop();
    fileListener = null;
  }

  try {
    // 创建新的监听器
    console.log('🚀 [IPC] 正在创建主进程文件监听器...');
    fileListener = new MainProcessFileListener(directoryPath, 1000, mainWindow);
    console.log('🚀 [IPC] 开始启动监听器...');
    fileListener.start();
    console.log('✅ [IPC] 监听器启动成功');
    return true;
  } catch (error) {
    console.error('❌ [IPC] 启动监听器失败:', error);
    return false;
  }
});

ipcMain.handle('stop-listening', async () => {
  console.log('🛑 [IPC] 收到停止监听请求');

  if (fileListener) {
    fileListener.stop();
    fileListener = null;
    console.log('✅ [IPC] 监听器已停止');
    return true;
  }

  console.log('ℹ️ [IPC] 监听器未运行');
  return true;
});

app.whenReady().then(() => {
  console.log('🚀 [主进程] 应用启动');
  console.log(`📱 [主进程] 平台: ${process.platform}`);
  console.log(`🔧 [主进程] 是否打包: ${app.isPackaged}`);
  console.log(`📁 [主进程] 应用路径: ${app.getAppPath()}`);
  console.log(`📁 [主进程] 用户数据路径: ${app.getPath('userData')}`);

  createWindow();
  createMenu();

  app.on('activate', () => {
    console.log('🔄 [主进程] 应用激活');
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// 文件监听器管理器
let fileListener: MainProcessFileListener | null = null;

// 全局错误处理
process.on('uncaughtException', (err) => {
  console.error('Uncaught Exception:', err);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});